package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.archive.entity.Category;
import com.example.archive.mapper.CategoryMapper;
import com.example.archive.service.CategoryService;
import com.example.archive.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result<Boolean> addCategory(Category category) {
        if (category.getCategoryName() == null || category.getCategoryName().isEmpty()) {
            return Result.fail(400, "分类名称不能为空");
        }
        QueryWrapper<Category> query = new QueryWrapper<>();
        query.eq("category_name", category.getCategoryName());
        if (categoryMapper.selectOne(query) != null) {
            return Result.fail(400, "分类名称已存在");
        }
        category.setCreatedAt(new Date());
        int insert = categoryMapper.insert(category);
        return insert > 0 ? Result.success(true) : Result.fail(500, "添加分类失败");
    }

    @Override
    public Result<Boolean> updateCategory(Category category) {
        if (category.getCategoryId() == null) {
            return Result.fail(400, "分类ID不能为空");
        }
        if (category.getCategoryName() == null || category.getCategoryName().isEmpty()) {
            return Result.fail(400, "分类名称不能为空");
        }
        QueryWrapper<Category> query = new QueryWrapper<>();
        query.eq("category_name", category.getCategoryName());
        Category existingCategory = categoryMapper.selectOne(query);
        if (existingCategory != null && !existingCategory.getCategoryId().equals(category.getCategoryId())) {
            return Result.fail(400, "分类名称已存在");
        }
        int update = categoryMapper.updateById(category);
        return update > 0 ? Result.success(true) : Result.fail(500, "更新分类失败");
    }

    @Override
    public Result<Boolean> deleteCategory(Integer categoryId) {
        if (categoryId == null) {
            return Result.fail(400, "分类ID不能为空");
        }
        int delete = categoryMapper.deleteById(categoryId);
        return delete > 0 ? Result.success(true) : Result.fail(500, "删除分类失败");
    }

    @Override
    public Result<List<Category>> listCategories(String search) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            queryWrapper.like("category_name", search).or().like("description", search);
        }
        List<Category> categories = categoryMapper.selectList(queryWrapper);
        return Result.success(categories);
    }
} 